package com.rf.admin.service.impl;

import com.rf.admin.domain.Drug;
import com.rf.admin.domain.Order;
import com.rf.admin.domain.Register;
import com.rf.admin.mapper.RegisterMapper;
import com.rf.admin.service.DrugService;
import com.rf.admin.service.OrderService;
import com.rf.admin.service.RegisterService;
import com.rf.common.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Mr.R
 * @description 针对表【sys_register(用户挂号表)】的数据库操作Service实现
 * @createDate 2022-04-21 20:28:39
 */
@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private RegisterMapper registerMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private DrugService drugService;

    @Override
    public List<Register> getRegisters(String orderId) {
        return registerMapper.getRegisters(orderId);
    }

    @Override
    public boolean delByIdRRegister(String id) {
        return registerMapper.deleteById(id) > 0;
    }

    @Override
    public boolean updateRegister(String id) {
        return false;
    }

    @Override
//    @Transactional(timeout = 5)  // springboot事务 超时5秒就回滚
    public boolean saveRegister(String userId,Register[] registers){
        Order order = new Order();
        String id = UUIDUtils.getId();  // 生成一个id 由order和 register 双表联查使用
        order.setOrderId(id);
        int money = 0;
        try {
            for (Register register : registers) {
                register.setOrderId(id);
                money += register.getMoney();
                if (registerMapper.insert(register) <= 0){
                    throw new Exception("插入未成功,已回滚");
                }
                if (!drugService.updateDrugNumber(register.getProductId(),register.getProductNum())){
                    throw new Exception("插入未成功,已回滚");
                }
            }
            order.setUserId(userId);
            order.setOrderAmount(money);
            order.setOrderInfo("药品订单");
            if (!orderService.insertOrder(order)){
                throw new Exception("插入未成功,已回滚");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

}
